﻿using HCMS.CommonDtos;
using HCMS.Entities.OAuth2;
using HCMS.Extensions;
using HCMS.IServices.OAuth2;
using HCMS.Services.OAuth2;
using HCMS.Utils;
using HCMS.Web.Manage.Filter;
using Microsoft.AspNetCore.Mvc;

namespace HCMS.Web.Manage.Controllers.Module.OAuth2
{
    /// <summary>
    /// OAuth 2.0 应用管理
    /// </summary>
    public class OAuth2AppController : ModuleController
    {
        private readonly IOAuth2AppAppService oauth2AppAppService;
        private readonly IOAuth2AccessTokenAppService oauth2AccessTokenAppService;

        public OAuth2AppController(
            IOAuth2AppAppService oauth2AppAppService, 
            IOAuth2AccessTokenAppService oauth2AccessTokenAppService)
        {
            this.oauth2AppAppService = oauth2AppAppService;
            this.oauth2AccessTokenAppService = oauth2AccessTokenAppService;
        }

        #region 列表
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult List()
        {
            return View($"{BasePath}/OAuth2App/List.cshtml");
        }

        /// <summary>
        /// 列表 Ajax
        /// </summary>
        /// <returns></returns>
        [ActionName("List")]
        [HttpPost]
        public async Task<IActionResult> PostList()
        {
            var searchArgs = new SearchArgsDto()
            {
                Status = Request.Form["status"].ToInt(9999),

                SearchName = Request.Form["searchName"].ToString(""),
                SearchKey = Request.Form["searchKey"].ToString("")
            };

            var pager = new PagerArgsDto()
            {
                CurrentPageIndex = Request.Form["page"].ToInt(1),
                PageSize = Request.Form["limit"].ToInt(10)
            };

            var result = await oauth2AppAppService.ManageList(searchArgs, pager);

            return Json(new { code = 0, data = result.Data, count = result.PagerInfo.RowCount, msg = "ok" });
        }
        #endregion

        #region 新增、编辑、保存
        /// <summary>
        /// 新增
        /// </summary>
        /// <returns></returns>
        public IActionResult Add()
        {
            var model = new OAuth2App();
            return View($"{BasePath}/OAuth2App/Edit.cshtml", model);
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> Edit(int id)
        {
            if (id <= 0)
            {
                return Content("参数无效");
            }

            var model = await oauth2AppAppService.BaseFirstOrDefaultAsync(t => t.Id == id);
            if (model == null)
            {
                return Content($"没有找到【id：{id}】应用信息");
            }

            return View($"{BasePath}/OAuth2App/Edit.cshtml", model);
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="oAuth2App"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Save(OAuth2App oAuth2App)
        {
            OAuth2App? result = null;

            if (oAuth2App == null)
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "参数错误" });
            }
            if (string.IsNullOrWhiteSpace(oAuth2App.Name))
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "请填写应用名称" });
            }
            if (string.IsNullOrWhiteSpace(oAuth2App.Secret))
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "请填写应用密钥" });
            }

            var entity = await oauth2AppAppService.BaseFirstOrDefaultAsync(t => t.Id == oAuth2App.Id);
            if (entity != null)
            {
                await TryUpdateModelAsync(entity);
                entity.Remark = oAuth2App.Remark ?? "";
                entity.UpdateTime = DateTime.Now;
                entity.UpdateUser = CurrentAdmin.AdminName;

                result = await oauth2AppAppService.BaseUpdateAsync(entity);
            }
            else
            {
                entity = new OAuth2App()
                {
                    CreateTime = DateTime.Now,
                    CreateUser = CurrentAdmin.AdminName,
                    UpdateTime = DateTime.Now,
                    UpdateUser = CurrentAdmin.AdminName
                };
                await TryUpdateModelAsync(entity);
                entity.Remark = oAuth2App.Remark ?? "";

                result = await oauth2AppAppService.BaseInsertAsync(entity);
            }

            if (result != null)
            {
                return Json(new AjaxResultDto() { Message = "处理成功" });
            }
            else
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "处理失败" });
            }
        }
        #endregion

        #region AccessToken 列表
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult AccessTokenList()
        {
            return View($"{BasePath}/OAuth2App/AccessTokenList.cshtml");
        }

        /// <summary>
        /// 列表 Ajax
        /// </summary>
        /// <returns></returns>
        [ActionName("AccessTokenList")]
        [HttpPost]
        public async Task<IActionResult> PostAccessTokenList()
        {
            var searchArgs = new SearchArgsDto()
            {
                FromId = Request.Form["fromId"].ToInt(0)
            };

            var pager = new PagerArgsDto()
            {
                CurrentPageIndex = Request.Form["page"].ToInt(1),
                PageSize = Request.Form["limit"].ToInt(10)
            };

            var result = await oauth2AccessTokenAppService.ManageList(searchArgs, pager);

            return Json(new { code = 0, data = result.Data, count = result.PagerInfo.RowCount, msg = "ok" });
        }
        #endregion

        //---------------- 私有 ---------------

        #region 生成随机密钥
        /// <summary>
        /// 生成随机密钥
        /// </summary>
        /// <returns></returns>
        [DefaultPermission]
        [HttpGet]
        public IActionResult GetRandomSecret()
        {
            var result = RandomUtil.GetRandomString("", 43);
            return Json(new AjaxResultDto() { Result = result });
        }
        #endregion
    }
}